package com.bocai.yuweiwangluo.activity;


import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bocai.yuweiwangluo.R;
import com.bocai.yuweiwangluo.View.RoundImageView;
import com.bocai.yuweiwangluo.alipay.AlipayApi;
import com.bocai.yuweiwangluo.base.BaseActivity;
import com.bocai.yuweiwangluo.bean.BaseBean;
import com.bocai.yuweiwangluo.bean.OrderBean;
import com.bocai.yuweiwangluo.event.MainEvent;
import com.bocai.yuweiwangluo.net.MyOkHttpClient;
import com.bocai.yuweiwangluo.net.sourceforge.simcpux.WxPayApi;
import com.bocai.yuweiwangluo.utils.ImageLoaderUtil;
import com.bocai.yuweiwangluo.utils.SharePrefencesUtil;
import com.bocai.yuweiwangluo.utils.UrlData;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

/**
 * 订单详情界面
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener
{
    @ViewInject(R.id.ll_checkcoupons)
    LinearLayout llCheckCoupons;
    @ViewInject(R.id.iv_pic)
    RoundImageView ivType;
    @ViewInject(R.id.tv_title)
    TextView tvTitle;
    @ViewInject(R.id.tv_time)
    TextView tvTime;
    @ViewInject(R.id.tv_addr)
    TextView tvAddr;
    @ViewInject(R.id.tv_price)
    TextView tvPrice;
    @ViewInject(R.id.tv_quan_count)
    TextView tvCount;
    @ViewInject(R.id.tv_money)
    TextView tvMoney;
    @ViewInject(R.id.cb_weipay)
    CheckBox cbWeiPay;
    @ViewInject(R.id.cb_alipay)
    CheckBox cbAliPay;
    @ViewInject(R.id.btn_pay)
    Button btnPay;
    @ViewInject(R.id.ll_quan)
    LinearLayout llquan;
    @ViewInject(R.id.tv_coupon)
    TextView tvCoupon;
    private String content;
    private String type_id;
    public static MyOkHttpClient myOkHttpClient;
    private static String id;
    public static  String[] strings;
    private AlipayApi mAlipayApi;
    private OrderBean orderBean;
    private String money="0";
    private String couponId="-1";
    private String totalPrice;
    private static final int RESPONSE_SUCCEED = 1;
    private static final int RESPONSE_FAILED = 2;
    private static  int requestType=0;
    String[] days;
    private BaseBean baseBean=new BaseBean();
    public Handler mHandler=new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            Gson gson = new Gson();
            Log.e("result", result);
            try
            {
                switch (msg.what)
                {
                    case RESPONSE_SUCCEED:
                        if(requestType==1)
                        {
                            hideLoading();
                            //获取订单详情
                            orderBean=gson.fromJson(result,OrderBean.class);
                            tvCount.setText(orderBean.getRow().getCoupon_num());
                            initData();
                        }else if(requestType==2)
                        {
                            baseBean=gson.fromJson(result,BaseBean.class);
                            if(baseBean.getState()==0)
                            {
                                if(!"-1".equals(couponId))
                                {
                                    submitCouponState();
                                }else
                                {
//                                    hideLoading();
                                    showError("预约成功");
                                    setResult(2000);
//                                OrderDetailActivity.this.finish();
                                    startActivity(new Intent(OrderDetailActivity.this,MyVenueActivity.class));
                                }
                            }else
                            {
                                hideLoading();
                                showError(baseBean.getMsg());
                            }
                            //提交订单
                        }else if(requestType==3)
                        {
//                            hideLoading();
                            baseBean=gson.fromJson(result,BaseBean.class);
                            if(baseBean.getState()==0)
                            {
                                showError("预约成功");
//                                setResult(2000);
//                                OrderDetailActivity.this.finish();
                                startActivity(new Intent(OrderDetailActivity.this,MyVenueActivity.class));
                            }else
                            {
                                showError(baseBean.getMsg());
                            }
                            //修改使用过的优惠券状态
                        }
                        break;
                    case RESPONSE_FAILED:
                        hideLoading();
                        showError(result);
                        break;
                }
            } catch (Exception e)
            {
            }
        }
    };

    private void getOrder()
    {
        try
        {
            requestType=1;
            showLoading();
            myOkHttpClient.getOrder(UrlData.BASEURL + UrlData.GETORDER, SharePrefencesUtil.getUser_id(this), id, mHandler);

        }catch (Exception e)
        {

        }
    }
    @Override
    protected int contentView()
    {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void setData()
    {
        ViewUtils.inject(this);
        initToolbar("订单详情");
        myOkHttpClient=new MyOkHttpClient(this,this);
        content=getIntent().getStringExtra("content");
        id= getIntent().getStringExtra("id");
        getOrder();
        initEvent();
    }

    private void initData()
    {
        try
        {
            type_id=orderBean.getRow().getType_id();
            //place_info_id=4&order_day=20160112&order_time=14:00
            strings=content.split("&");
            tvTitle.setText(orderBean.getRow().getTitle());
            ImageLoaderUtil.loaderImageDefault(UrlData.IMAGEURL + orderBean.getRow().getPic(), ivType);
            tvAddr.setText(orderBean.getRow().getAddr());
            tvPrice.setText(orderBean.getRow().getItem_price()+"元/每人");
            days=strings[1].split("=")[1].split("_");
            String [] times=strings[2].split("=")[1].split("_");
            StringBuffer stringBuffer=new StringBuffer();
            for (int i=0;i<days.length;i++)
            {
                stringBuffer.append(days[i]);
                stringBuffer.append(" "+times[i]+"    ");
            }
            tvTime.setText(stringBuffer.toString());
            tvMoney.setText(Double.parseDouble(orderBean.getRow().getItem_price())*days.length+"");
//            totalPrice=Double.parseDouble(orderBean.getRow().getPrice())*days.length+"";
            totalPrice=Double.parseDouble(orderBean.getRow().getItem_price())*days.length+"";
        }catch (Exception e)
        {

        }

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        llCheckCoupons.setOnClickListener(this);
        btnPay.setOnClickListener(this);
        cbAliPay.setOnClickListener(this);
        cbWeiPay.setOnClickListener(this);
    }
    /**
     * 支付宝支付
     */
    private void alipay()
    {
        if (mAlipayApi == null)
        {
            mAlipayApi = new AlipayApi(this);
            mAlipayApi.setmOnPayComplateListener(new AlipayApi.OnPayComplateListener()
            {
                @Override
                public void onPayComplete(String outTradeNo)
                {
                    Toast.makeText(OrderDetailActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    // TODO 充值完成后
                    submitOrder();
                }

            });
        }

//        mAlipayApi.pay(mAlipayApi.getOrderInfo("场馆预定", "预定" + orderBean.getRow().getTitle() + "场馆",
//                0.01 + ""));
        mAlipayApi.pay(btnPay, orderBean.getRow().getTitle(),totalPrice);
    }

    public void submitOrder() {
        try{
//            showLoading();
            requestType=2;
            myOkHttpClient.addVenue(UrlData.BASEURL+UrlData.ADDVENUE,strings[0].split("=")[1],strings[1].split("=")[1],strings[2].split("=")[1], SharePrefencesUtil.getUser_id(this),mHandler);
        }catch (Exception e)
        {
            e.printStackTrace();

        }
    }
    private void submitCouponState() {
        try{
            requestType=3;
            MyOkHttpClient myOkHttpClient=new MyOkHttpClient(this,this);
            myOkHttpClient.updataCoupon(UrlData.BASEURL + UrlData.UPDATECOUPON, SharePrefencesUtil.getUser_id(this), couponId, mHandler);
        }catch (Exception e)
        {

        }
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        super.onEventMainThread(event);
        submitOrder();
    }

    /**
     * 微信支付
     */
    private void weiChatPay()
    {
        com.bocai.yuweiwangluo.net.sourceforge.simcpux.WxPayApi wxPayApi=new WxPayApi(this);
        double tPrice=Double.parseDouble(totalPrice);
        tPrice=tPrice*100;
        int price= (int) Math.ceil(tPrice);
        wxPayApi.pay("场馆预定",price+"" );

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        try{
            if(requestCode==1000)
            {
                if (resultCode==-1)
                {
                    if(data!=null)
                    {
                        money=data.getStringExtra("money");
                        couponId=data.getStringExtra("couponId");
                        if(!("0".equals(money)))
                        {
                            llquan.setVisibility(View.GONE);
                            tvCoupon.setVisibility(View.VISIBLE);
                            tvCoupon.setText("您使用了" + money + "元优惠券");
//                            totalPrice=(Double.parseDouble(orderBean.getRow().getPrice())*days.length-Double.parseDouble(money))+"";
                            totalPrice=(Double.parseDouble(orderBean.getRow().getItem_price())*days.length-Double.parseDouble(money))+"";
                            tvMoney.setText(totalPrice);
                        }
                    }
                }
            }
        }catch (Exception e)
        {}
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ll_checkcoupons:
                Intent intent=new Intent(this,CouponsCheckActivity.class);
                startActivityForResult(intent, 1000);
                break;
            case R.id.btn_pay:
                if(cbAliPay.isChecked())
                {

                    alipay();
                }else if(cbWeiPay.isChecked())
                {
                    weiChatPay();
                }else if(!cbAliPay.isChecked()&!cbWeiPay.isChecked())
                {
                    Toast.makeText(this,"请选择支付方式",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.cb_alipay:
                if(cbWeiPay.isChecked())
                {
                    cbWeiPay.setChecked(false);
                }
                break;
            case R.id.cb_weipay:
                if(cbAliPay.isChecked())
                {
                    cbAliPay.setChecked(false);
                }
                break;
        }

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            setResult(2000);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
